/*
 * Treebank.cpp
 *
 *  Created on: Dec 18, 2014
 *      Author: Phong
 */

#include "Treebank.h"
#include <vector>
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include "Utils.h"
#include "Depstruct.h"

using namespace std;

Treebank::~Treebank() {
	for (int i = 0; i < this->size(); i++)
		Deptree::free(storage[i]);
}

Treebank* Treebank::load(string fname, Dictionary* vocaDic, Dictionary* posDic, Dictionary* deprelDic) {
	cout << "load " << fname << endl;
	Treebank* tb = new Treebank();
	fstream reader(fname, ios::in);
	DEP* rows = new DEP[1000];
	string line;
	int length = 0;

	while (getline(reader, line)) {
		vector<string> comps = Utils::splitStringWoRegex(line, "\t");
		if (comps.size() == 1) {
			Depstruct* ds = Depstruct::create(rows, length, vocaDic, posDic, deprelDic);
			Deptree* tree = ds->toDepTree();
			tb->storage.push_back(tree);

			Depstruct::free(ds);

			if (tb->size() % 1000 == 0) {
				cout << tb->size() << "\r" << flush;
			}
			length = 0;
		}
		else {
			length++;
			rows[length-1] = DEP(stoi(comps[0]), comps[1], comps[4], stoi(comps[6]), comps[7]);
		}
	}

	delete[] rows;

	cout << tb->size() << " trees" << endl;
	reader.close();
	return tb;
}

vector<Depstruct*> Treebank::getDsBank() {
	vector<Depstruct*> ret(size());
	for (int i = 0; i < size(); i++)
		ret[i] = storage[i]->ds;
	return ret;
}
